package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * <新闻 - 长城网> 解析类
 *
 * @author KK
 *
 */
public class HebeiNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		String[] regex={
				"http://.*.hebei.com.cn/.*[0-9]+/[0-9]+/[0-9]+/[0-9]+.shtml"
		};

		return RegexUtils.matchAny(url,regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {

		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		String commnetNum=null;
		String clickNum=null;
		Document doc=Jsoup.parse(htmltxt);

		title=doc.select("h1#docTitle").text();
		if (StringUtils.isBlank(title)){
			title=doc.select("title").text();
			if (title.contains("_")) title=StringUtils.substringBefore(title, "_");
		}
		date=DateUtils.matchDate(doc.select("span.docRelTime").text());
		if (date==null){
			date=JSoupUtils.matchDate(doc, "来源：");
		}
		if (date==null){
			date=DateUtils.matchDate(doc.select(".nph_set_title").text());
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div#fontzoom"));
		if (StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select(".nph_cnt"));
		}
		if (date==null){
			date=DateUtils.matchDate(doc.select("#pubtime_baidu").text());
		}
		author=JSoupUtils.matchAuthor(doc, "稿源：","来源：");
		NewsMeta news=new NewsMeta();
		news.setUrl(url);
		news.setAuthor(author);
		news.setType(1);
		news.setTitle(StringUtils.trimSpace(title));
		news.setCommentNum(NumberUtils.parseInt(commnetNum));
		news.setClickNum(NumberUtils.parseInt(clickNum));
		news.setContent(StringUtils.trimSpace(content));
		news.setDate(date);
		return news;
	}



	public static void main(String[] args) {
		HebeiNewsAnalyse a=new HebeiNewsAnalyse();
		String url="http://edu.hebei.com.cn/system/2016/11/05/017521172.shtml";
		System.out.println(a.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=a.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
